package sbpme.designer.command;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.commands.Command;

import sbpme.designer.model.Activity;
import sbpme.designer.model.ProcessDiagram;
import sbpme.designer.model.Transition;

public class ActivityDeleteCommand extends Command {

	private Activity activity;
	private ProcessDiagram parent;
	private int index = -1;
	private List sourceConnections = new ArrayList();
	private List targetConnections = new ArrayList();

	public void execute() {
		executeOrRedo();
	}
	
	public void undo() {
		parent.addActivity(index, activity);
		restoreConnections();
	}
	
	public void redo() {
		executeOrRedo();
	}

	protected void executeOrRedo() {
		deleteConnections(activity);
		index = parent.getActivities().indexOf(activity);
		parent.removeActivity(activity);
	}

	private void deleteConnections(Activity activity) {
		sourceConnections.addAll(activity.getSourceTransitions());
		for (int i = 0; i < sourceConnections.size(); i++) {
			Transition transition = (Transition) sourceConnections.get(i);
			transition.getSource().removeTargetTransition(transition);
			activity.removeSourceTransition(transition);
		}
		targetConnections.addAll(activity.getTargetTransitions());
		for (int i = 0; i < targetConnections.size(); i++) {
			Transition transition = (Transition) targetConnections.get(i);
			transition.getTarget().removeSourceTransition(transition);
			activity.removeTargetTransition(transition);
		}
	}

	private void restoreConnections() {
		for (int i = 0; i < sourceConnections.size(); i++) {
			Transition transition = (Transition) sourceConnections.get(i);
			transition.getTarget().addTargetTransition(transition);
			transition.getSource().addSourceTransition(transition);
		}
		sourceConnections.clear();
		for (int i = 0; i < targetConnections.size(); i++) {
			Transition transition = (Transition) targetConnections.get(i);
			transition.getSource().addSourceTransition(transition);
			transition.getTarget().addTargetTransition(transition);
		}
		targetConnections.clear();
	}

	public void setChild(Activity activity) {
		this.activity = activity;
	}

	public void setParent(ProcessDiagram processDiagram) {
		this.parent = processDiagram;
	}


}
